package com.aiyige.utils.banner;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.Scroller;

import java.lang.reflect.Field;

/**
 * Created by zhuyakun on 2017/10/16.
 */

public class Banner extends ViewPager {
    boolean scrollable = true;
    BannerScroller bannerScroller;

    public Banner(Context context) {
        super(context);
        init();
    }

    public Banner(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        try {
            Class<?> viewpager = ViewPager.class;
            Field scroller = viewpager.getDeclaredField("mScroller");
            scroller.setAccessible(true);
            bannerScroller = new BannerScroller(getContext(), new DecelerateInterpolator());
            bannerScroller.setBannerScrollDurationMs(900);
            scroller.set(this, bannerScroller);
        } catch (Exception e) {
        }
    }

    public boolean isScrollable() {
        return scrollable;
    }

    public void setScrollable(boolean scrollable) {
        this.scrollable = scrollable;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return scrollable && super.onTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return scrollable && super.onInterceptTouchEvent(ev);
    }


    public class BannerScroller extends Scroller {

        private int bannerScrollDurationMs = 500;

        public BannerScroller(Context context) {
            super(context);
        }

        public BannerScroller(Context context, Interpolator interpolator) {
            super(context, interpolator);
        }

        public BannerScroller(Context context, Interpolator interpolator, boolean flywheel) {
            super(context, interpolator, flywheel);
        }

        public int getBannerScrollDurationMs() {
            return bannerScrollDurationMs;
        }

        public void setBannerScrollDurationMs(int bannerScrollDurationMs) {
            this.bannerScrollDurationMs = bannerScrollDurationMs;
        }

        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, bannerScrollDurationMs);
        }
    }
}
